package tech.aichan.AiQA.utils;

import tech.aichan.AiQA.common.ErrorCode;
import tech.aichan.AiQA.exception.BusinessException;
import jakarta.annotation.Resource;
import org.springframework.mail.MailException;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.stereotype.Component;

import java.util.Random;

/**
 * @author mengyu
 * @date 2024/03/8 14:22
 */
@Component
public class SendMailUtil {
    @Resource
    private JavaMailSender mailSender;
    public Integer sendMail(String to) {
        Random rand = new Random();
        int code = rand.nextInt(900000) + 100000;
        // 存redis
        String subject = "AiChanTech | 邮箱验证码";
        String content = "您正在进行邮箱验证操作，操作码为:\n" + code +
                "\n" +
                "验证码 5 分钟内有效。";
        try {
            SimpleMailMessage message = new SimpleMailMessage();
            message.setFrom("AiChanTeck@163.com");
            message.setTo(to);
            message.setSubject(subject);
            message.setText(content);
            mailSender.send(message);
        } catch (MailException e) {
            throw new BusinessException(ErrorCode.SYSTEM_ERROR,e.getMessage());
        }
        return code;
    }
}
